package xdu.lz.netty.e_zerocopy;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author lizhen
 * @date 2019/8/15 11:03
 * @desc 　netty零拷贝
 */
public class ZeroCopyServer {
    public static void main(String[] args) throws Exception{

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8899));
//        //获取serverSelector来配置参数
//        ServerSocket serverSocket = serverSocketChannel.socket();
//
//        //表示对于长时间处于空闲状态的Socket, 是否要自动把它关闭,要在bind前设置
//        serverSocket.setReuseAddress(true);
//
//        serverSocket.bind(new InetSocketAddress(8899));

//        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4096);
        ByteBuffer byteBuffer = ByteBuffer.allocate(4096);

        while (true) {
            System.out.println("===========");
            int i=0;
//            ExecutorService executorService = Executors.newSingleThreadExecutor(Executors.defaultThreadFactory());
//            executorService.submit(() -> {});
            //获取客户端连接
            SocketChannel socketChannel = serverSocketChannel.accept();
            //设置成阻塞，等待客户端传数据
            socketChannel.configureBlocking(true);

            int readCount = 0;
//            long total = 0;

            while ( readCount != -1 ) {
                i++;
                try {
                    readCount = socketChannel.read(byteBuffer);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                //The position is set to zero and the mark is discarded.
                byteBuffer.rewind();

                // The limit is set to the current position and then
                // the position is set to zero.  If the mark is defined then it is discarded.
//                byteBuffer.flip();
            }
            System.out.println("i="+i);
        }

    }

}
